package com.yuntongxun.ecdemo.ui.account;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.base.CCPFormInputView;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings;
import com.yuntongxun.ecdemo.common.utils.ECPreferences;
import com.yuntongxun.ecdemo.common.utils.FileAccessor;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.core.ClientUser;
import com.yuntongxun.ecdemo.core.ContactsCache;
import com.yuntongxun.ecdemo.rest.CookieManager;
import com.yuntongxun.ecdemo.rest.RetrofitUtil;
import com.yuntongxun.ecdemo.rest.interfaces.LoginInterface;
import com.yuntongxun.ecdemo.rest.interfaces.UserInterface;
import com.yuntongxun.ecdemo.rest.models.LoginSubmit;
import com.yuntongxun.ecdemo.rest.models.ServerResult;
import com.yuntongxun.ecdemo.rest.models.UserAccountModel;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.ECSuperActivity;
import com.yuntongxun.ecdemo.ui.LauncherActivity;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecdemo.ui.contact.ContactLogic;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECInitParams;
import com.yuntongxun.ecsdk.SdkErrorCode;

import java.io.InvalidClassException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Jorstin on 2015/3/18.
 */
public class LoginActivity extends ECSuperActivity implements
		View.OnClickListener {

	private Button _signBtn;
	private CCPFormInputView _accountInput;
	private CCPFormInputView _passwordInput;
	private ECProgressDialog _postingDialog;
	private String _imAccount;
	private String _imPwd;
	private Button _sendVerifyCodeBtn;
	private CountDownTimer _countDownTimer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initResourceRefs();

		getTopBarView().setTopBarToStatus(1, -1,
				R.drawable.btn_style_green,
				null,
				null,
				getString(R.string.app_name), null, this);

		registerReceiver(new String[] { SDKCoreHelper.ACTION_SDK_CONNECT });
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		dismissPostingDialog();
		if(_countDownTimer != null) {
			_countDownTimer.cancel();
		}
	}

	private void initResourceRefs() {

		_accountInput = (CCPFormInputView) findViewById(R.id.account);
		_accountInput.requestFocus();
		_passwordInput = (CCPFormInputView) findViewById(R.id.password);
		_signBtn = (Button) findViewById(R.id.sign_in_button);
		_signBtn.setOnClickListener(this);
		_sendVerifyCodeBtn = (Button)findViewById(R.id.send_verification_code);
		_sendVerifyCodeBtn.setOnClickListener(this);

		((Button)findViewById(R.id.switch_to_login)).setOnClickListener(this);
		((Button)findViewById(R.id.switch_to_register)).setOnClickListener(this);
		((Button)findViewById(R.id.submit_to_register)).setOnClickListener(this);

		_countDownTimer = new CountDownTimer(60000, 1000) {

			public void onTick(long millisUntilFinished) {
				_sendVerifyCodeBtn.setText(String.format("%s(%d)", getString(R.string.send_verification_code), millisUntilFinished / 1000));
			}

			public void onFinish() {
				_sendVerifyCodeBtn.setText(R.string.send_verification_code);
				_sendVerifyCodeBtn.setEnabled(true);
			}

		};
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onActivityInit() {
		// super.onActivityInit();
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_login;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
			case R.id.sign_in_button:
				loginIn();
				break;
			case R.id.switch_to_login:
				switchToLogin();
				break;
			case R.id.switch_to_register:
				switchToRegister();
				break;
			case R.id.submit_to_register:
				register();
				break;
			case R.id.send_verification_code:
				sendVerificationCode();
				break;
			case R.id.text_right:
				break;
			case R.id.text_left:
				break;
			default:
				break;
		}
	}

	private void loginECIM() {
		String appKey = FileAccessor.getAppKey();
		String token = FileAccessor.getAppToken();

		ClientUser clientUser = new ClientUser(_imAccount);
		clientUser.setAppKey(appKey);
		clientUser.setAppToken(token);
		clientUser.setLoginAuthType(ECInitParams.LoginAuthType.PASSWORD_AUTH);
		clientUser.setPassword(_imPwd);
		CCPAppManager.setClientUser(clientUser);

		SDKCoreHelper.init(this, ECInitParams.LoginMode.FORCE_LOGIN);
	}

	/**
	 * 关闭对话框
	 */
	private void dismissPostingDialog() {
		if (_postingDialog == null || !_postingDialog.isShowing()) {
			return;
		}
		_postingDialog.dismiss();
		_postingDialog = null;
	}

	private void doLauncherAction() {
		try {
			Intent intent = new Intent(this, LauncherActivity.class);
			intent.putExtra("launcher_from", 1);
			// 注册成功跳转
			startActivity(intent);
			finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void saveAccount() throws InvalidClassException {

		String appKey = FileAccessor.getAppKey();
		String token = FileAccessor.getAppToken();

		ClientUser clientUser = new ClientUser(_imAccount);
		clientUser.setAppKey(appKey);
		clientUser.setAppToken(token);
		clientUser.setLoginAuthType(ECInitParams.LoginAuthType.PASSWORD_AUTH);
		clientUser.setPassword(_imPwd);
		CCPAppManager.setClientUser(clientUser);

		ECPreferences.savePreference(ECPreferenceSettings.SETTINGS_REGIST_AUTO,
				clientUser.toString(), true);

		ECPreferences.savePreference(ECPreferenceSettings.SETTINGS_MY_ID,
				_imAccount, true);

		ArrayList<ECContacts> objects = ContactLogic.initContacts();
		objects = ContactLogic.converContacts(objects);
		ContactSqlManager.insertContacts(objects);
	}

	@Override
	protected void handleReceiver(Context context, Intent intent) {
		// super.handleReceiver(context, intent);
		int error = intent.getIntExtra("error", -1);
		if (SDKCoreHelper.ACTION_SDK_CONNECT.equals(intent.getAction())) {
			// 初始注册结果，成功或者失败
			if (SDKCoreHelper.getConnectState() == ECDevice.ECConnectState.CONNECT_SUCCESS
					&& error == SdkErrorCode.REQUEST_SUCCESS) {

				dismissPostingDialog();
				try {
					saveAccount();
				} catch (InvalidClassException e) {
					e.printStackTrace();
				}
				ContactsCache.getInstance().load();
				doLauncherAction();
				return;
			}
			if (intent.hasExtra("error")) {
				if (SdkErrorCode.CONNECTTING == error) {
					return;
				}
				if (error == -1) {
					ToastUtil.showMessage("请检查登陆参数是否正确[" + error + "]");
				}else {
					dismissPostingDialog();
				}
				ToastUtil.showMessage("登录失败，请稍后重试[" + error + "]");
			}
			dismissPostingDialog();
		}
		
	}

	@Override
	protected boolean isEnableSwipe() {
		return false;
	}

	@Override
	public boolean isEnableRightSlideGesture() {
		return false;
	}

	private void loginIn() {
		hideSoftKeyboard();
		String account = _accountInput.getText().toString().trim();
		String password = _passwordInput.getText().toString().trim();

		if (!isValidPhoneNumber(account)) {
			ToastUtil.showMessage(R.string.invalid_phone_number);
			return;
		}

		if (!isValidPassword(password)) {
			ToastUtil.showMessage(R.string.invalid_password);
			return;
		}

		if(_postingDialog == null) {
			_postingDialog = new ECProgressDialog(this, R.string.login_posting);
			_postingDialog.show();
		}

		LoginInterface loginInterface = RetrofitUtil.createRestApi(LoginInterface.class);

		loginInterface.login(new LoginSubmit(account, password), new Callback<UserAccountModel>() {
			@Override
			public void success(UserAccountModel userAccount, Response response) {

				CookieManager.getInstance().executeSetCookie(response);

				_imAccount = userAccount.getContactAccount();
				_imPwd = userAccount.getImPwd();

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						loginECIM();
					}
				});
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				LogUtil.i("loginInterface::ERROR=" + retrofitError);
				dismissPostingDialog();
				String msg = retrofitError.getMessage();
				if(msg != null) {
					if(msg.toUpperCase().indexOf("TIMEOUT") >= 0) {
						ToastUtil.showMessage(R.string.connect_timeout);
					} else {
						ToastUtil.showMessage(msg);
					}
				} else {
					ToastUtil.showMessage(R.string.unknown_error);
				}
			}
		});
	}

	private void register() {
		hideSoftKeyboard();
		String phone = ((CCPFormInputView)findViewById(R.id.register_phone)).getText().toString().trim();
		String vCode = ((EditText)findViewById(R.id.register_verification_code)).getText().toString().trim();
		String name = ((CCPFormInputView)findViewById(R.id.register_name)).getText().toString().trim();
		String password = ((CCPFormInputView)findViewById(R.id.register_password)).getText().toString().trim();
		String confirmPassword = ((CCPFormInputView)findViewById(R.id.register_confirm_password)).getText().toString().trim();

		if (!isValidPhoneNumber(phone)) {
			ToastUtil.showMessage(R.string.invalid_phone_number);
			return;
		}

		if (!isValidVerificationCode(vCode)) {
			ToastUtil.showMessage(R.string.invalid_verification_code);
			return;
		}

		if (!isValidName(name)) {
			ToastUtil.showMessage(R.string.invalid_name);
			return;
		}

		if (!isValidPassword(password)) {
			ToastUtil.showMessage(R.string.invalid_password);
			return;
		}

		if (!password.equals(confirmPassword)) {
			ToastUtil.showMessage(R.string.invalid_confirm_password);
			return;
		}

		if(_postingDialog == null) {
			_postingDialog = new ECProgressDialog(this, R.string.please_wait);
			_postingDialog.show();
		}

		UserInterface userInterface = RetrofitUtil.createRestApi(UserInterface.class);

		userInterface.register(phone, vCode, name, password, new Callback<UserAccountModel>() {
			@Override
			public void success(UserAccountModel userAccount, Response response) {

				CookieManager.getInstance().executeSetCookie(response);

				_imAccount = userAccount.getContactAccount();
				_imPwd = userAccount.getImPwd();

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						loginECIM();
					}
				});
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				LogUtil.i("register::ERROR=" + retrofitError);
				dismissPostingDialog();
				ToastUtil.showMessage(retrofitError.getMessage());
			}
		});
	}

	private void switchToLogin() {
		findViewById(R.id.login_form).setVisibility(View.VISIBLE);
		findViewById(R.id.register_form).setVisibility(View.GONE);
	}

	private void switchToRegister() {
		findViewById(R.id.login_form).setVisibility(View.GONE);
		findViewById(R.id.register_form).setVisibility(View.VISIBLE);
	}

	private void sendVerificationCode() {
		hideSoftKeyboard();
		String phone = ((CCPFormInputView)findViewById(R.id.register_phone)).getText().toString().trim();

		if (!isValidPhoneNumber(phone)) {
			ToastUtil.showMessage(R.string.invalid_phone_number);
			return;
		}

		if(_postingDialog == null) {
			_postingDialog = new ECProgressDialog(this, R.string.please_wait);
			_postingDialog.show();
		}

		UserInterface userInterface = RetrofitUtil.createRestApi(UserInterface.class);

		userInterface.sendVerificationCode(phone, 1, new Callback<ServerResult>() {
			@Override
			public void success(ServerResult serverResult, Response response) {
				//
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						dismissPostingDialog();
						_sendVerifyCodeBtn.setEnabled(false);
						_countDownTimer.start();
					}
				});
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				LogUtil.i("sendVerificationCode::ERROR=" + retrofitError);
				dismissPostingDialog();
				ToastUtil.showMessage(retrofitError.getMessage());
			}
		});
	}

	private boolean isValidPhoneNumber(String phoneNumber) {
		Pattern pattern = Pattern.compile("^(13|14|15|16|17|18|19)\\d{9}$");
		Matcher matcher = pattern.matcher(phoneNumber);
		return matcher.matches();
	}

	private boolean isValidVerificationCode(String verificationCode) {
		Pattern pattern = Pattern.compile("^\\d{4}$");
		Matcher matcher = pattern.matcher(verificationCode);
		return matcher.matches();
	}

	private boolean isValidName(String name) {
		Pattern pattern = Pattern.compile("^[^`~!@#$%^&*()<>\\[\\]{}\\-=+,./\\?;:'\\\\\"\\|\\s]{2,10}$");
		Matcher matcher = pattern.matcher(name);
		return matcher.matches();
	}

	private boolean isValidPassword(String pwd) {
		return pwd != null && pwd.length() >= 6;
	}
}
